package wang.xinqiu.mysqlcontrol.data

data class CacheStats(
    val size: Int,
    val maxSize: Int,
    val hitRate: Float
)

class QueryCache {
    private val cache = mutableMapOf<String, QueryResult>()
    private val maxSize = 50
    private var hits = 0
    private var misses = 0
    
    fun get(query: String, database: String): QueryResult? {
        val key = "$database:$query"
        val result = cache[key]
        if (result != null) {
            hits++
        } else {
            misses++
        }
        return result
    }
    
    fun put(query: String, database: String, result: QueryResult) {
        val key = "$database:$query"
        if (cache.size >= maxSize) {
            cache.remove(cache.keys.first())
        }
        cache[key] = result
    }
    
    fun clear() {
        cache.clear()
        hits = 0
        misses = 0
    }
    
    fun getCacheStats(): CacheStats {
        val total = hits + misses
        val hitRate = if (total > 0) hits.toFloat() / total else 0f
        return CacheStats(cache.size, maxSize, hitRate)
    }
    
    fun getStats(): String {
        return "缓存条目: ${cache.size}/$maxSize"
    }
}